package com.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.common.permission.PermissionCheck;
import com.demo.common.permission.PermissionKey;
import com.demo.common.vo.Result;
import com.demo.entity.SysRole;
import com.demo.entity.vo.IdRequest;
import com.demo.entity.vo.SysRoleSearchReq;
import com.demo.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 角色管理controller
 */
@RestController
@RequestMapping("/sys/role")
@PermissionCheck(PermissionKey.VIEW_ROLE_MANAGER)
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    /**
     * 新增角色
     * @param sysRole
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody SysRole sysRole){
        try{
            sysRoleService.save(sysRole);
        }catch (DuplicateKeyException e){
            return Result.error("角色名称"+sysRole.getRoleName()+"已存在");
        }
        return Result.success();
    }

    /**
     * 删除角色
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody @Valid IdRequest request){
        sysRoleService.removeRole(request.getId());
        return Result.success();
    }

    /**
     * 更新角色名称
     * @param sysRole
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody SysRole sysRole){
        if(sysRole.getId()==null){
            return Result.error("更新角色id不能为空");
        }
        try {
            sysRoleService.updateById(sysRole);
        } catch (DuplicateKeyException e){
            return Result.error("角色名称"+sysRole.getRoleName()+"已存在");
        }
        return Result.success();
    }

    /**
     * 角色列表
     * @param req
     * @return
     */
    @PostMapping("/list")
    public Result list(@RequestBody SysRoleSearchReq req){
        Page<SysRole> page=new Page<>(req.getCurrent(),req.getSize());
        QueryWrapper<SysRole> queryWrapper=new QueryWrapper();
        queryWrapper.like(StringUtils.isNotBlank(req.getRoleName()),SysRole.ROLE_NAME,req.getRoleName());
        sysRoleService.page(page,queryWrapper);
        return Result.success(page);
    }

}
